package com.sh.healthtv.webconfig;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sh.healthtv.app.AppContext;
import com.sh.healthtv.app.AppManager;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.HisColObserveble;
import com.sh.healthtv.database.LitepalTVCollectUitils;
import com.sh.healthtv.database.LitepalTVHtoryUitils;
import com.sh.healthtv.database.model.CollectionProgram;
import com.sh.healthtv.database.model.HistoryProgram;
import com.sh.healthtv.net.entity.Epg;
import com.sh.healthtv.ui.PlayerActivity;
import com.sh.healthtv.view.NewToast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhouyucheng on 2017/4/1  14:14.
 */

public class KnowledgeJs implements ActivityFunc {
    private String TAG = "KnowledgeJs";
    private Activity mActivity;
    private String name;

    public String getName() {
        return name;
    }

    public KnowledgeJs(Activity mActivity) {
        this.mActivity = mActivity;
    }

    @JavascriptInterface
    public void finish() {
        exitBy2Click();
    }

    @JavascriptInterface
    @Override
    public void refreshTitle(String title) {
        this.name = title;
        System.out.println(title);
    }

    @JavascriptInterface
    @Override
    public void share(String a, String b, boolean c, String d) {
        System.out.println("微信分享回调" + a + ":a" + b + ":b" + c + "：c" + d + ":d");
        System.out.println("   调用了分享");
    }

    @JavascriptInterface
    @Override
    public void saveJkyxBitmap(byte[] temp, String bitName) {
        Bitmap bt = getBitmapFromByte(temp);
        File f = new File("/sdcard/Jkyx/" + bitName + ".jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bt.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            Toast.makeText(mActivity, "图形保存异常！", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            Toast.makeText(mActivity, "图形保存异常！", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        Toast.makeText(mActivity, "图形保存成功！", Toast.LENGTH_LONG).show();
    }

    @JavascriptInterface
    @Override
    public void onKeyClick(int onKeyCode) {

    }

    @JavascriptInterface
    @Override
    public void programPlay(String id, String name, String imageUrl) {
        Log.i("1111", "programPlay:programPlay ");
        HistoryProgram program = null;
        try {
            Epg epg = getEpg(id, name, imageUrl);
            Log.i(TAG, "programPlay: " + epg);
            List<HistoryProgram> hisList = LitepalTVHtoryUitils.queryTVHtory(epg.getUseid());
            List<CollectionProgram> colList = LitepalTVCollectUitils.queryTVCollect(epg.getUseid());
            if (hisList != null && hisList.size() > 0) {
                epg.setHisPlayed(1);
                switch (Integer.valueOf(hisList.get(0).getPlayState())) {
                    case 0:
                        epg.setHisState(0);
                        epg.setProgress(hisList.get(0).getPlayTime());
                        break;
                    case -1:
                        epg.setHisState(-1);
                        break;
                    case -2:
                        epg.setHisState(-2);
                        break;
                }
            } else {
                epg.setHisPlayed(0);
            }
            if (colList != null && colList.size() > 0) {
                epg.setIsBeenCollect("1");
            } else {
                epg.setIsBeenCollect("0");
            }
            AppContext.setCURRENTEPG(epg);
            startActivity(epg);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mActivity, "节目转换失败，请换个试试！", Toast.LENGTH_SHORT).show();
        }

    }

    private Epg getEpg(String id, String name, String imageUrl) {
        Epg epg = null;
        try {
            epg = new Epg();
            epg.setUseid(id);
            epg.setName(name);
            epg.setImageUrl(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return epg;
    }

    @JavascriptInterface
    @Override
    public void getColList() {
        HisColObserveble.getInstance().getColList(LitepalTVCollectUitils.queryAllTVCollect());
    }

    @JavascriptInterface
    @Override
    public void getHisList() {
        HisColObserveble.getInstance().getHisList(LitepalTVHtoryUitils.queryAllTVHtory());
    }

    public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

    /*
    * 封装的GSON解析工具类，提供泛型参数
    *
     */
    public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {
        Gson gson = new Gson();
        T result = gson.fromJson(jsonData, type);
        return result;
    }

    private void startActivity(Epg epg) {
        Intent in = new Intent();
        in.putExtra("programId", epg.getUseid());
        in.putExtra("programName", epg.getName());
        in.putExtra("progress", epg.getProgress());
        in.putExtra("isConnect", epg.getIsBeenCollect());
        in.setClass(mActivity, PlayerActivity.class);
        mActivity.startActivity(in);
    }


    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            NewToast.makeText(mActivity, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            mActivity.finish();
            AppManager.getAppManager().appExit(mActivity);
        }
    }
}
